#!/bin/bash

APP_PATH=`pwd`
#这里可替换为你自己的执行程序，其他代码无需更改
APP_NAME=`find -name *.jar `
#java 执行路径 暂时没有用
# JAVA_HOME=/usr/local/java/jdk1.8.0_151/bin/java
PID_FILE=${APP_PATH}/server.pid


#使用说明，用来提示输入参数
usage() {
    echo "Usage: sh 执行脚本.sh [start|stop|restart|status]"
    exit 1
}

echo "find jar ${APP_NAME} , current pid is `cat ${PID_FILE}`"

#检查程序是否在运行
is_exist(){
  current_pid=`cat ${PID_FILE}`
  pid=`ps -ef|grep ${current_pid} |grep -v grep|awk '{print $2}' `

  #如果不存在返回1，存在返回0
  if [[ -z "${pid}" ]]; then
   return 1
  else
    return 0
  fi
}

#启动方法
start(){
  cat /dev/null > nohup.out
  is_exist
  if [[ $? -eq "0" ]]; then
    echo "${APP_NAME} is already running. pid is ${current_pid} ."
    
  else
    echo "${APP_NAME} starting"
    source /etc/profile
    nohup java -Xms1024m  -Xmx1024m  -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=256m  -jar  ${APP_NAME} >/dev/null 2>&1 & 
    echo $! > ${PID_FILE}
    echo "${APP_NAME} started"
  fi
  exit 0
}

#停止方法
stop(){
  is_exist
  if [[ $? -eq "0" ]]; then
    echo "${APP_NAME} stop"
    kill -9 `cat ${PID_FILE}`
    rm ${PID_FILE}
    echo "${APP_NAME} stoped"
  else
    echo "${APP_NAME} is not running"
  fi
}

#输出运行状态
status(){
  is_exist
  if [[ $? -eq "0" ]]; then
    echo "${APP_NAME} is running. pid  is ${current_pid}"
  else
    echo "${APP_NAME} is NOT running."
  fi
}

#重启
restart(){
  echo "${APP_NAME} restarting"
  stop
  start
  echo "${APP_NAME} restarted"
}

#根据输入参数，选择执行对应方法，不输入则执行使用说明
case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  *)
    usage
    ;;
esac
